import React, { useState } from 'react'
import PropTypes from 'prop-types'
import { nanoid } from 'nanoid'

const Header = (props) => {
    const [title, setTitle] = useState('');
    const addItem = () => {
        if (!title) {
            return alert("添加内容不能为空！");
        }
        props.addItem({
            title,
            id: nanoid(4),
            done: false
        })
        setTitle('');
    }
    const changeTitle = (e) => {
        var title = e.currentTarget.value.trim();
        if (!title) {
            return false;
        }
        setTitle(title);
    }
    const keySubmit = (e) => {
        if (e.keyCode == 13) {
            addItem();
        }
    }
    return (
        <div className='header-wrapper' onKeyUp={keySubmit}>
            <input onChange={changeTitle} value={title} />
            <button className='btn' onClick={addItem}>添加</button>
        </div>
    )
}

Header.prototype = {
    addItem: PropTypes.func.isRequired
}

export default Header
